package com.upyun.playdemo.presenter;

import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.upyun.playdemo.mode.VideoData;
import com.upyun.playdemo.utils.Constant;
import com.upyun.playdemo.utils.OPENLOG;
import cz.msebera.android.httpclient.Header;

/**
 * Video Presenter 层.
 */
public class VideoPresenter implements IVideoContract.IVideoPresenter {

    IVideoContract.IVideoView mVideoView;

    public VideoPresenter(IVideoContract.IVideoView videoView) {
        mVideoView = videoView;
    }

    @Override
    public void getVideoList(String key, int page, int size) {
        OPENLOG.D(Constant.VIDEO_URL);
        AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.add("keyword", key);
        params.add("page", page + "");
        params.add("size", size + "");
        asyncHttpClient.get(Constant.ROOT_ADDR + Constant.VIDEO_URL, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                String str = new String(responseBody);
                try {
                    Gson gson = new Gson();
                    VideoData videoData = gson.fromJson(str, VideoData.class);
                    onVideoListSuccess(videoData);
                } catch (Exception e) {
                    e.printStackTrace();
                    onVideoListFailure();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                onVideoListFailure();
            }
        });
    }

    private void onVideoListSuccess(VideoData videoData) {
        mVideoView.updateVideoList(videoData);
    }

    private void onVideoListFailure() {
        mVideoView.updateVideoFailure();
    }

}
